<?php



namespace app\admin\controller;

use app\admin\service\NodeService;
use app\common\controller\AdminBase;
use library\Controller;
use library\tools\Data;
use think\Db;

/**
 * 系统用户管理
 * Class User
 *
 * @package app\admin\controller
 * @author  Anyon <zoujingli@qq.com>
 * @date    2017/02/15 18:12
 */
class User extends Base {

    /**
     * 指定当前数据表
     *
     * @var string
     */
    public $table = 'SysUser';

    /**
     * 系统用户管理
     *
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index() {
        if (request()->isPost()) {
            $this->title = '系统用户管理';
            $query = $this->_query($this->table)
                          ->like('username,phone,mail')
                          ->dateBetween('login_at');
            $res = $query->equal('status')
                         ->where(['is_deleted' => '0'])
                         ->order('id desc')
                         ->page(true, false, false, request()->param('limit'));
            $this->success( $res ,'数据获取成功');
        } else {
            $this->title = '系统用户管理';
            $query = $this->_query($this->table)
                          ->like('username,phone,mail')
                          ->dateBetween('login_at');
            $query->equal('status')
                  ->where(['is_deleted' => '0'])
                  ->order('id desc')
                  ->page();
        }

    }

    /**
     * 添加系统用户
     *
     * @auth true
     */
    public function add() {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑系统用户
     *
     * @auth true
     */
    public function edit() {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 修改用户密码
     *
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass() {
        $this->applyCsrfToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            $this->_form($this->table, 'pass');
        } else {
            $post = $this->request->post();
            if ($post['password'] !== $post['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            $result = NodeService::checkpwd($post['password']);
            if (empty($result['code'])) $this->error($result['msg']);
            if (Data::save($this->table, ['id'       => $post['id'],
                                          'password' => md5($post['password'])
            ], 'id')) {
                $this->success([],'密码修改成功，下次请使用新密码登录！');
            } else {
                $this->error(1,'密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 表单数据处理
     *
     * @param array $data
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data) {
        if ($this->request->isPost()) {
            if ($data['password'] && strlen($data['password']) != 32) {
                $data['password'] = md5($data['password']);
            }
            NodeService::applyUserAuth();
            $data['authorize'] = (isset($data['authorize']) && is_array($data['authorize'])) ? join(',', $data['authorize']) : '';
            if (isset($data['id'])) {
                unset($data['username']);
            } elseif (Db::name($this->table)
                        ->where(['username' => $data['username']])
                        ->count() > 0) {
                $this->error('用户账号已经存在，请使用其它账号！');
            }
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->authorizes = Db::name('SystemAuth')
                                  ->where(['status' => '1'])
                                  ->order('sort desc,id desc')
                                  ->select();
        }
    }

    /**
     * 禁用系统用户
     *
     * @auth true
     */
    public function forbid() {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用系统用户
     *
     * @auth true
     */
    public function resume() {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }

    /**
     * 删除系统用户
     *
     * @auth true
     */
    public function remove() {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }

    public function getUserInfo() {


        if (!$this->userId) {
            $this->error(1, '用户识别码为空');
        }

	    $user = Db::name('sys_user')
	              ->find($this->userId);
	    if (!$user) {
		    $this->error(1, '当前用户不存在');
	    }
	    $fields = [
		    'm1.id',
		    'm1.title',
		    'm1.path',
		    'm1.parent_id'
	    ];
	    if ($user['id'] === 10000) {
		    $menuList = Db::name('sys_menu')
		                  ->alias('m1')
		                  ->field($fields)
		                  ->order('m1.order')
		                  ->select();
	    } else {
		    $menuIds = Db::name('sys_role')
		                 ->where('id', 'in', $user['role_ids'])
		                 ->column('menu_ids');
		    $menuIds = array_unique(explode(',', implode(',', $menuIds)));
		    $menuList = Db::name('sys_menu')
		                  ->alias('m1')
		                  ->distinct(true)
		                  ->field($fields)
		                  ->join('wx_sys_menu m2', 'FIND_IN_SET(m1.id,concat(m2.parent_ids,",",m2.id))')
		                  ->where('m2.id', 'in', $menuIds)
		                  ->order('m1.order')
		                  ->select();
        }

        $res = [
            'userid'   => $this->userId,
            'username' => $user['name'],
            'menuList' => $menuList
        ];
        $this->success($res);


    }

}
